import {get_advisor_available, create_advising} from '../../utils/backend'

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    advisorInfo:{},
    available: '',
    begin_waiting:'',
    timer:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      advisorInfo: JSON.parse(options.advisorInfoBean),
      available: false
    })
    console.log(this.data.advisorInfo);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var begin_waiting = parseInt(Date.parse(new Date())/1000)
    this.setData({
      begin_waiting: begin_waiting
    })

    var that = this
    var advisor_available_interval = setInterval(function(){
      //轮询查询咨询师状态：若变为空闲，则1.停止轮询，2.创建咨询，3.转入chat页面
      get_advisor_available(that.data.advisorInfo.id)
      wx.event.on("advisor_available",()=>{
        clearInterval(advisor_available_interval)//1.停止轮询
        var timestamp = Date.parse(new Date())//2.创建咨询
        var created = parseInt(timestamp/1000)
        var advising = {
          start_timestamp: timestamp,
          advisorInfo: that.data.advisorInfo,
          created: created,
          ended: '',
          score: ''
        }
        create_advising(advising)
        wx.redirectTo({//3.转入chat页面
          url: '../chat/chat',
        })
      })
    },2000)

    var timer_interval = setInterval(function(){
      //轮询更新等待时间
      var timestamp = Date.parse(new Date())//当前时间戳  
      var diff = (parseInt(timestamp/1000) - that.data.begin_waiting)
      var h = parseInt(diff/3600)
      var m = (parseInt(diff/60))%60
      var s = diff%60
      that.setData({
        timer: (h>9?h:'0'+h)+':'+(m>9?m:'0'+m)+':'+(s>9?s:'0'+s)
      })
    },1000)
  },

  cancelWaiting(){
    wx.showModal({
      title:"提示",
      content:"确定不再等等吗？",
      confirmText:"再等等",
      cancelText:"不等了",
      success(res){
        if(res.cancel){
          wx.navigateBack({
            delta: 1,
          })
        }
      }
    })
  }
})